﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Slaughter;
using Traceable.App.DTOS;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Slaughter
{
    public class GetSlaughterListHandler : IRequestHandler<GetSlaughterListCommand, ApiResult<SlaughterDto>>
    {
        private readonly IBaseRepository<Slaughter_Table> _slaughterRepository;
        private readonly IBaseRepository<Traceable_Table> _traceableRepositry;
        private readonly IMapper _mapper;

        public GetSlaughterListHandler(IBaseRepository<Slaughter_Table> slaughterRepository, IMapper mapper, IBaseRepository<Traceable_Table> traceableRepositry)
        {
            _slaughterRepository = slaughterRepository;
            _mapper = mapper;
            _traceableRepositry = traceableRepositry;
        }
        /// <summary>
        /// 获取屠宰基本信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<SlaughterDto>> Handle(GetSlaughterListCommand request, CancellationToken cancellationToken)
        {
            ApiResult<SlaughterDto> result = new ApiResult<SlaughterDto>();

            var slaughter = _slaughterRepository.GetAll().Where(p =>p.Batch_Id==request.Batch_Id &&!p.IsDelete).FirstOrDefault();
            if(slaughter!=null)
            {
                result.Code = StatusEnum.OK;
                result.Data = _mapper.Map<SlaughterDto>(slaughter);
                result.Message = "获取成功";
                var goods = _traceableRepositry.GetAll().Where(p => p.Batch == request.Batch_Id).FirstOrDefault();
                if (goods.Perfect <= 70)
                {
                    goods.Perfect += 30;
                }
                var res = _traceableRepositry.Update(goods);
            }
            return Task.FromResult(result);
        }
    }
}
